<?php

namespace app\shop\library\delivery;

use app\shop\enums\delivery\DeliveryApiProvider;
use app\shop\library\delivery\implements\Kd100Implement;
use app\shop\library\delivery\implements\WechatImplement;
use think\facade\Cache;

class DeliveryProvider
{
    private object $provider;

    private string $cachePrefix = 'delivery-tracks:';
    private int    $cacheExpire = 7200;

    public function __construct(string $apiType)
    {
        $this->provider = match ($apiType) {
            DeliveryApiProvider::KD_100 => new Kd100Implement(),
            DeliveryApiProvider::WECHAT => new WechatImplement(),
        };
    }

    /**
     * @param array $params
     * <br>delivery_no 物流单号
     * <br>delivery_company_code 物流公司编码
     * <br>receiver_phone 收件人手机号
     * <br>openid 下单用户openid(微信小程序物流查询组件必须传)
     * @return array
     */
    public function query(array $params): array
    {
        $cacheKey  = $this->cachePrefix . $params['delivery_no'];
        $cacheData = Cache::get($cacheKey);
        if ($cacheData) {
            return $cacheData;
        }

        $result = $this->provider->query($params);
        if ($result) {
            Cache::set($cacheKey, $result, $this->cacheExpire);
        }

        return $result;
    }
}